import AppointmentClient from './AppointmentClient'
import { getCourts } from '@/lib/courtsService'
import { getAppointments, createCourseAppointment,addCourseAppointmentAssistantCoach,addCourseAppointmentClient,addCourseAppointmentPackage,removeCourseAppointmentPackage,removeCourseAppointmentAssistantCoach,removeCourseAppointmentClient, updateCourseAppointmentStatus } from '@/lib/appointmentService'
import { getCoursePackages } from '@/lib/coursePackagesService'
import { getCurrentUser, getAllUsers } from '@/lib/userService'
import { getCampuses } from '@/lib/campusService'
import { formatDateForAPI } from '@/lib/dateUtils'

async function bookAppointment(appointment) {
  'use server'
  try {
    const newAppointment = {
      branch_campus_id: appointment.branch_campus_id,
      coach_id: appointment.coach_id,
      court_id: appointment.court_id,
      start_time: formatDateForAPI(appointment.start_time),
      end_time: formatDateForAPI(appointment.end_time),
      status: 'pending',
      teaching_commission_rate: parseFloat(appointment.teaching_commission_rate),
      memo: appointment.memo || '',
    }
    const clientsWithPackages = JSON.parse(appointment.selected_clients_with_packages)
    const coachesWithRates = JSON.parse(appointment.selected_coaches_with_rates)
    // 检查教练是否选择
    console.log(appointment)
    if(appointment.coach_id === '') {
      return {
        success: false,
        message: "请选择一个主教练",
      };
    }
    if (clientsWithPackages.length < 1) {
      return {
        success: false,
        message: "至少需要选择一个学生极其课程包",
      };
    }

    const createdAppointment = await createCourseAppointment(newAppointment)

    for (const coach of coachesWithRates) {
      const addedCoach = await addCourseAppointmentAssistantCoach(createdAppointment.id, {
        coach_id: coach.assistant_id,//助教ID
        teaching_commission_rate: coach.rate,//提成比例
      })
    }
    for (const client of clientsWithPackages) {
      const addedClient = await addCourseAppointmentClient(createdAppointment.id, {
        client_id: client.parent,//学员ID
      })
    }
    for (const client of clientsWithPackages) {
      const addedPackage = await addCourseAppointmentPackage(createdAppointment.id, {
        course_package_id: client.child,//课程包ID
        status: 'active',
        memo: ''
      })
    }
    return {
      success: true,
      message: '预约成功',
      createdAppointment
    }
  } catch (error) {
    console.error('预约失败:', error)
    return {
      success: false,
      message: error.message || '预约失败，请稍后重试'
    }
  }
}

async function cancelAppointment(appointmentInfo) {
  'use server'
  const { appointment_id } = appointmentInfo
  try {
    await updateCourseAppointmentStatus(appointment_id, { status: 'cancelled' })
    return { success: true, message: '预约已取消' }
  } catch (error) {
    console.error(error.message)
    return { success: false, message: error.message }
  }
}

export default async function AppointmentPage() {
  const currentUser = await getCurrentUser();
  // 判断当前用户是否是教练？？
  const campuses = await getCampuses({})
  return (
    <div className="container mx-auto px-4 w-full">
      <AppointmentClient
        currentUser={currentUser}
        initialCampuses={campuses}
        getCourts={getCourts}
        getAllUsers={getAllUsers}
        getCoursePackages={getCoursePackages}
        getAppointments={getAppointments}
        handleBookAppointment={bookAppointment}
        handleCancelAppointment={cancelAppointment}
      />
    </div>
  )
}